package com.ruoyi.project.hcy.task.service;

import com.ruoyi.project.hcy.task.domain.Task;
import com.ruoyi.project.hcy.task.mapper.TaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
public class FileUploadServiceImpl implements IFileUploadService {

    @Autowired
    TaskMapper taskMapper;

    @Override
    public int submitTask(String fileId, MultipartHttpServletRequest request) {
        String taskFile = System.currentTimeMillis() + fileId.substring(fileId.lastIndexOf("."));
        String deskFile = "src/main/resources/static/img/hcy/task/" + taskFile;
        String deskFile2 = "target/classes/static/img/hcy/task/" + taskFile;
        MultipartFile uploadFile = request.getFile("uploadFile");
        File file = new File(deskFile);
        File targetFile = new File(deskFile2);
        File parentFile = file.getParentFile();
        File parentFile1 = targetFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        if (!parentFile1.exists()) {
            parentFile1.mkdirs();
        }
        try {
            InputStream is = uploadFile.getInputStream();
            FileOutputStream fos = new FileOutputStream(file);
            FileOutputStream fos2 = new FileOutputStream(targetFile);
            byte[] buf = new byte[4096];
            int len;
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
                fos2.write(buf, 0, len);
                fos.flush();
                fos2.flush();
            }
            fos.close();
            fos2.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String taskIdStr = request.getParameter("taskId");
        Long taskId = Long.valueOf(taskIdStr);
        Task task = taskMapper.selectTaskById(taskId);
        Task newTask = new Task();
        newTask.setTaskFile(taskFile);
        newTask.setTaskId(taskId);
        return taskMapper.updateTask(newTask);
    }
}
